Python 使用 __ 开头的名字来定义特殊的方法和属性,它们有:
__init__()__repr__()__str__()__call__()__iter__()__add__()__sub__()__mul__()__rmul__()__class____name____init__()¶之前说到,在产生对象之后,我们可以向对象中添加属性。事实上,还可以通过构造方法,在构造对象的时候直接添加属性:
class Leaf(object):
"""
A leaf falling in the woods.
"""
def __init__(self, color='green'):
self.color = color
默认属性值:
leaf1 = Leaf()
print leaf1.color
传入有参数的值:
leaf2 = Leaf('orange')
print leaf2.color
回到森林的例子:
import numpy as np
class Forest(object):
""" Forest can grow trees which eventually die."""
def __init__(self):
self.trees = np.zeros((150,150), dtype=bool)
self.fires = np.zeros((150,150), dtype=bool)
我们在构造方法中定义了两个属性 trees 和 fires:
forest = Forest()
forest.trees
forest.fires
修改属性的值:
forest.trees[0,0]=True
forest.trees
改变它的属性值不会影响其他对象的属性值:
forest2 = Forest()
forest2.trees
事实上,__new__() 才是真正产生新对象的方法,__init__() 只是对对象进行了初始化,所以:
leaf = Leaf()
相当于
my_new_leaf = Leaf.__new__(Leaf)
Leaf.__init__(my_new_leaf)
leaf = my_new_leaf
__repr__() 和 __str__()¶class Leaf(object):
"""
A leaf falling in the woods.
"""
def __init__(self, color='green'):
self.color = color
def __str__(self):
"This is the string that is printed."
return "A {} leaf".format(self.color)
def __repr__(self):
"This string recreates the object."
return "{}(color='{}')".format(self.__class__.__name__, self.color)
__str__() 是使用 print 函数显示的结果:
leaf = Leaf()
print leaf
__repr__() 返回的是不使用 print 方法的结果:
leaf
回到森林的例子:
import numpy as np
class Forest(object):
""" Forest can grow trees which eventually die."""
def __init__(self, size=(150,150)):
self.size = size
self.trees = np.zeros(self.size, dtype=bool)
self.fires = np.zeros((self.size), dtype=bool)
def __repr__(self):
my_repr = "{}(size={})".format(self.__class__.__name__, self.size)
return my_repr
def __str__(self):
return self.__class__.__name__
forest = Forest()
__str__() 方法:
print forest
__repr__() 方法:
forest
__name__ 和 __class__ 为特殊的属性:
forest.__class__
forest.__class__.__name__